<?php
/* {
Citru - www.citru.se
See license.txt for copyright and license information.
} */

if(!defined("_CITRU")) {die('This file should not be accessed directly.');}
require_once 'Module.php';

class PageModule extends Module {
	
	protected $moduleTabs = array("templates", "edit", "add", "permissions");
	protected $moduleName = "PageModule";
	protected $instanceName;
	protected $dbModule;
	protected $permissions;
	
	/**
	 * Creates a new user module object
	 *
	 * @param string $instance 				name of the instance
	 * @param string $db_module 			database module to load data from
	 * @param arrau $permissions 			permissions to views
	 * @return void
	 */function __construct($instance, $db_module, $permissions) {
		$this->instanceName = $instance;
		$this->dbModule = $db_module;
		$this->permissions = $permissions;
	}
	
	/**
	 * Adds the necessary table for PageModule
	 *
	 * @return void
	 */
	public function installTables() {
		// No own table needed, uses pages
		
		// Add global permissions
		$params_perm = array(	'table' => 'Permissions',
        						'set' => array(	'module'=>$this->moduleName,
											'permissions'=>"templates=@admin\nedit=@admin\nadd=@admin\npermissions=@admin"));
        if(!$this->dbModule->insertRow($params_perm)) {
			throw new Exception('Could not create global permissions for '.$this->moduleName.'.');
		}
	}
	
	
	/**
	 * This module has no public view, so it just returns an empty string
	 *
	 * @return string		empty string
	 */
	public function getView() {
		return '';
	}
	
	/**
	 * Returns the selected tab of the admin view
	 *
	 * @param string $tab 		selected tab
	 * @return string			html for selected tab
	 */
	protected function getAdminTab($tab="view") {
		switch($tab) {
			case "edit":
				return $this->getEditForm();
			case "add":
				return $this->getAddTemplateForm();
			case "permissions":
				return $this->getPermissionsForm();
			default:
				return $this->getList();
		}
	}
	
	/**
	 * Returns a list of pages
	 *
	 * @return string			list of pages in html form
	 */
	private function getList() {
		if($this->permissions['templates'] != true) { return ''; }
		
		// Get the pages
		$rows = $this->findPageRows();
				
		$list = '<table>';
		$list .= '<tr><th class="citru_half_width">Template</th><th class="citru_half_width">Pages</th><th>Edit</th>';
		$i = 0;
		foreach($rows as $row) {
			$i++;
			if($i % 2 != 0) { $odd = ' class="citru_odd_element"'; } else { $odd = ''; }
			
			$page = split("\n", $row['page']);
			sort($page);
			foreach($page as $j=>$p) {
				if($j == 0) {
					$link = $this->generateTablink('edit', 'template_id='.$row['id']);
					$list .= '<tr'.$odd.'><td class="citru_table_hr">'.$row['template'].'</td><td class="citru_table_hr">'.$p.'</td><td class="citru_table_hr">'.$link.'</td></tr>';
				} else {
					$list .= '<tr'.$odd.'><td class="citru_table_hr"></td><td class="citru_table_hr">'.$p.'</td><td class="citru_table_hr"></td></tr>';
				}
			}
		}
		$list .= '</table>';
		
		return $list;
	}
	
	/**
	 * Returns a form for editing settings
	 *
	 * @param string $message 		a message to display at the end of the form
	 * @return string				html for the edit form
	 */
	private function getEditForm($message="") {
		if($this->permissions['edit'] != true) { return ''; }
		
		// Check if settings should be saved first.
		if($_POST['instance'] == "PageModule_$this->instanceName" && $_POST['action'] == "edit") {
			$message = $this->saveFormData();
		}

		$rows = $this->findPageRows();
		$templates = array();
		$template_ids = array();
		$template_data = $rows[0];
		if(preg_match("/^[0-9]+$/",$_GET['template_id'])) {
			$selected = $_GET['template_id'];
		} else {
			$selected = $rows[0]['id'];
		}
		foreach ($rows as $i=>$row) {
			$templates[] = $row['id'].'. '.$row['template'];
			$template_ids[] = $row['id'];
			
			if($row['id'] == $selected) {
				$template_data = $row;
				$selected_number = $i;
			}
		}
		

		if(count($pages) > 0 || count($titles) > 0) {
			if(count($pages) > count($titles)) { $titles = array_pad($titles, count($pages), ''); }
			if(count($pages) < count($titles)) { $pages = array_pad($pages, count($titles), ''); }
			array_multisort($pages, $titles);
		}
		
		$select_template_elements = array(array('form_start', 'method'=>'get'),
								array('hidden_custom', 'name'=>$this->moduleName.'_'.$this->instanceName, 'value'=>'edit'),
								array('fieldset_start', 'legend'=>'Change template'),
								array('label', 'for'=>'template', 'text'=>'Template: ', 'class'=>'citru_left citru_right_space'),
								array('input_select', 'name'=>'template_id', 'options'=>$templates, 'values'=>$template_ids, 'selected'=>$selected_number, 'class'=>'citru_left'),
								array('submit', 'value'=>'Change', 'icon'=>'refresh'),
								array('fieldset_end'),
								array('form_end'));
		$select_template = $this->generateForm($select_template_elements);
		
		$edit_template_elements = array(array('form_start'),
								array('hidden_instance'),
								array('hidden_action', 'value'=>'edit'),
								array('hidden_custom', 'name'=>'template_id', 'value'=>$selected),
								array('fieldset_start', 'legend'=>'Pages'),
								array('p', 'text'=>'Pages that are used with this template: '),
								array('label', 'for'=>'page_0', 'text'=>'Page name:', 'class'=>'citru_half_width'),
								array('label', 'for'=>'title_0', 'text'=>'Page title:', 'class'=>'citru_half_width', 'after'=>'<br />'));
								
								$pages = split("\n", $template_data['page']);
								$titles = split("\n", $template_data['title']);
								for($i=0; $i < count($pages)+1; $i++) {
									$edit_template_elements[] = array('input_text', 'name'=>'page_'.$i, 'value'=>$pages[$i], 'class'=>'citru_half_width');
									$edit_template_elements[] = array('input_text', 'name'=>'title_'.$i, 'value'=>$titles[$i], 'class'=>'citru_half_width', 'after'=>'<br />');
								}
								
		$edit_template_elements[] = array('fieldset_end');
		$edit_template_elements[] = array('fieldset_start', 'legend'=>'Rename or remove');
		$edit_template_elements[] = array('label', 'for'=>'rename', 'text'=>'New name for template:');
		$edit_template_elements[] = array('input_text', 'name'=>'rename', 'value'=>$template_data['template']);
		$edit_template_elements[] = array('input_checkbox', 'name'=>'remove', 'text'=>'Remove the template '.$template_data['template'].'.');
		$edit_template_elements[] = array('input_checkbox', 'name'=>'remove_confirm', 'text'=>'Yes, I\'m sure!');
		$edit_template_elements[] = array('fieldset_end');
		$edit_template_elements[] = array('footer_start');
		$edit_template_elements[] = array('custom', 'data'=>$message);
		$edit_template_elements[] = array('submit', 'value'=>'Save', 'icon'=>'save');
		$edit_template_elements[] = array('footer_end');
		$edit_template_elements[] = array('form_end');
		
		
		$edit_template = $this->generateForm($edit_template_elements);
		
		return $select_template.$edit_template;
	}
	
	/**
	 * Returns a form for editing settings
	 *
	 * @param string $message 			a message to display at the end of the form
	 * @return string					html for the form
	 */
	private function getAddTemplateForm($message="") {
		if($this->permissions['add'] != true) { return ''; }
		
		// Check if settings should be saved first.
		if($_POST['instance'] == "PageModule_$this->instanceName" && $_POST['action'] == "add") {
			$message = $this->addNewTemplate();
		}
		
		$add_template_elements = 	array(array('form_start'),
								array('hidden_instance'),
								array('hidden_action', 'value'=>'add'),
								array('fieldset_start', 'legend'=>'Add template'),
								array('label', 'for'=>'name', 'text'=>'Template name', 'after'=>'<br />'),
								array('input_text', 'name'=>'name'),
								array('fieldset_end'), 
								array('footer_start'),
								array('custom', 'data'=>$message),
								array('submit', 'value'=>'Add Template', 'icon'=>'add'),
								array('footer_end'),
								array('form_end'));
		$add_template = $this->generateForm($add_template_elements);
		
		return $add_template;
	}
	
	/**
	 * Updates a previous instance from form data
	 *
	 * @return string			a message of how things went
	 */
	private function saveFormData() {
		$template_id = $_POST['template_id'];
		
		// Check if the template should be removed
		$remove = $_POST['remove'];
		$remove_confirm = $_POST['remove_confirm'];
		
		if($remove === 'on' and $remove_confirm === 'on') {
			$params = array(	"table" => "Pages",
								"condition" => array(array( "id", "=", $template_id, "" )));
			$result = $this->dbModule->deleteRow($params);
			return '<p class="citru_event">Template removed.</p>';
		}
		
		// Get the page and title data collected in an array
		$i = 0;
		$page = array();
		$title = array();
		while(isset($_POST['page_'.$i])) {
			if($_POST['page_'.$i] != '' || $_POST['title_'.$i] != '') {
				$page[] = $_POST['page_'.$i];
				$title[] = $_POST['title_'.$i];
			}
			$i++;
		}
		
		// Check if the name should be changed
		$new_name = $_POST['rename'];
		if(strlen($new_name) < 1 || !preg_match("/^[a-zA-Z0-9_\-.]*$/",$new_name)) {
			return '<p class="citru_error">Template names can only contain alphanumerical characters, dash, underscore and period.</p>';
		}
		
		$page = implode("\n", $page);
		$title = implode("\n", $title);
		
		$set = array('page'=>$page, 'title'=>$title, 'template'=>$new_name);
		$params = array(	"table" => "Pages",
							"condition" =>	array(
											array( "id", "=", $template_id, "" )),
							"set" => 		$set );															
		$result = $this->dbModule->updateRow($params);
		
		if($result) { return '<p class="citru_event">Form data saved.</p>'; }
		return '<p class="citru_error">Error saving form data.</p>';
	}
	
	/**
	 * Adds a new user based on form data
	 *
	 * @return string			a message of how things went
	 */
	private function addNewTemplate() {
		$name = $_POST['name'];
	
		if(strlen($name) < 1 || !preg_match("/^[a-zA-Z0-9_\-.]*$/",$name)) {
			return '<p class="citru_error">Template names can only contain alphanumerical characters, dash, underscore and period.</p>';
		}

		$params = array(	"table" => "Pages",
							"set" =>   array('template' => $name));
																	
		$result = $this->dbModule->insertRow($params);
		
		return '<p class="citru_event">The template has been added.</p>';
	}
	
	/**
	 * Returns all the pages
	 *
	 * @return array 			an array of user-rows (which also are arrays of values for id, name and groups)
	 */
	private function findPageRows() {
		$params = array(	"table" => "Pages",
							"columns" => "id, template, page, title",
							"condition" =>	array(
											array( "id", ">", "0", "" )),
							"order" => 'id');
		
		$pages = $this->dbModule->findAll($params);
		return $pages;
	}
	
	/**
	 * Returns a specific page
	 *
	 * @param integer $user_id 		user id to find
	 * @return array 				array of user data
	 */
	private function findPageRow($user_id) {
		$id = intval($user_id);
		$params = array(	"table" => "Pages",
							"columns" => "id, template, page, title",
							"condition" =>	array(
											array( "id", "=", "0", $id )),
							"order" => 'ID ASC');
		
		$user = $this->dbModule->findFirst($params);
		return $user;
	}
	
}

?>
